const express = require('express');
const fs = require('fs').promises;
const path = require('path');

const app = express();
const PORT = 30008;

// 创建异步路由处理器
async function handleJsonRequest(req, res, jsonFile) {
    try {
        const JSON_PATH = path.join(__dirname,  'data', jsonFile);
        const rawData = await fs.readFile(JSON_PATH,  'utf-8');
        let jsonData = JSON.parse(rawData);
        // 新增参数拦截逻辑
        if (req.path  === '/api/asset/detail' && req.query.id)  {
            const id = req.query.id;
            console.log(`[${new  Date().toISOString()}] 拦截到 ID 参数: ${id}`);

            // 这里可以添加针对 id 的参数处理逻辑
            // 例如：过滤数据、附加参数到响应体等
            jsonData = jsonData[id];
        }

        // 新增：POST请求体日志（调试用）
        if (req.method  === 'POST') {
            console.log(`[${new  Date().toISOString()}] POST Body:`, req.body);
        }
        if (req.method === 'GET') {
            console.log(`[${new  Date().toISOString()}] GET QUERY:`, req.query)
        }

        // 增强响应头配置
        res.header({
            'Content-Type': 'application/json; charset=utf-8',
            'Cache-Control': 'no-cache',
            'X-Custom-Header': 'Express-5.1'
        });

        // 添加调试信息
        jsonData.serverInfo  = {
            runtime: `Node ${process.version}`,
            timestamp: new Date().toISOString()
        };

        res.status(200).json(jsonData);
    } catch (error) {
        console.error(`[${new  Date().toISOString()}] Error:`, error);
        res.status(500).json({
            error: 'SERVER_ERROR',
            message: 'Failed to process JSON data',
            details: error.message
        });
    }
}

// 配置路由
const routes = [
    { path: '/api/asset/detail', method: 'get', jsonFile: 'assetDetail.json'  },
    { path: '/data', method: 'get', jsonFile: 'assetDetail.json'  }, // 兼容旧路径
    { path: '/sys/sysattachment/list', method: 'get', jsonFile: 'sysattachmentlist.json'  },
    { path: '/api/catalog/list', method: 'get', jsonFile: 'apiCatalogList.json'  },
    { path: '/api/catalog/listNode', method: 'get', jsonFile: 'apiCatalogListNode.json'  },
    { path: '/api/catalog/listAsset', method: 'get', jsonFile: 'apiCatalogListAsset.json', },
    { path: '/api/catalog', method: 'post', jsonFile: 'catalog.json', },
    { path: '/link/data/catalog', method: 'post', jsonFile: 'linkDataCatalog.json', },
    { path: '/api/catalog/listAsset/nation', method: 'get', jsonFile: 'nationAsset.json'}
];

// 修改：根据method动态注册路由
routes.forEach(route  => {
    if (route.method  === 'get') {
        app.get(route.path,  (req, res) => handleJsonRequest(req, res, route.jsonFile));
    } else if (route.method  === 'post') {
        app.post(route.path,  (req, res) => handleJsonRequest(req, res, route.jsonFile));
    }
});


// 启动服务
app.listen(PORT,  () => {
    console.log(`[${new  Date().toISOString()}] 服务已启动于 http://localhost:${PORT}`);
    console.log('  尝试访问：');
    routes.forEach(route  => {
        console.log(`   - ${route.path}:  http://localhost:${PORT}${route.path}`);
    });
});